import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_widgets/resources/kq_images.dart';
import 'package:kq_flutter_widgets/resources/l10n/kq_intl.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_widgets/widgets/dragView/kq_drag_list_view.dart';

enum DrawerPositionType {
  ///左边抽屉
  drawerPositionTypeLeft,

  ///右边边抽屉
  drawerPositionTypeRight
}

class KqDrawer<T> extends StatefulWidget {
  ///抽屉样式
  final DrawerPositionType? drawerPositionType;

  /// 抽屉宽度 默认：KqScreenUtil().screenWidth - 60.r
  final double? width;

  /// 离顶部的距离，默认在导航栏下方
  final double? top;

  /// 是否支持拖拽
  final bool? isSupportDrag;

  /// 自定义标题栏
  final Widget? titleBar;

  /// 标题
  final String? title;

  /// 标题样式
  final TextStyle? titleStyle;

  /// 数据
  final List<T> Function()? drawerData;

  /// 内容自定义
  final Widget Function()? customDrawerContent;

  /// 文本内容回调
  final String Function(T data)? drawItemContent;

  /// 是否选中回调
  final bool Function(T data)? drawItemSelectStatus;

  /// 事件
  final void Function(KqDrawerState state, T data)? onTap;

  /// 自定义底部视图 KqTabView 可通过state.reload()刷新页面
  final Widget Function(KqDrawerState state, List<T> newData)?
      customBottomWidget;

  /// 拖动后数据源换位置
  final Function(List<T> data)? onDrop;

  /// 底部视图文本
  // final List<String> Function()? bottomButtonTitles;

  // /// 底部视图文本颜色
  // final List<Color> Function()? bottomButtonTxtColors;

  // /// 底部视图背景颜色
  // final List<Color> Function()? bottomButtonBgColors;

  // /// 底部视图背景颜色
  // final List<Color> Function()? bottomButtonBorderColors;

  /// 控制抽屉开关
  final GlobalKey<ScaffoldState> drawerGlobalKey;

  const KqDrawer(
      {this.drawerPositionType = DrawerPositionType.drawerPositionTypeRight,
      this.width,
      this.top,
      this.isSupportDrag,
      this.titleBar,
      this.title,
      this.titleStyle,
      this.drawerData,
      this.customDrawerContent,
      this.drawItemContent,
      this.drawItemSelectStatus,
      this.onTap,
      this.customBottomWidget,
      this.onDrop,
      // this.bottomButtonTitles,
      // this.bottomButtonTxtColors,
      // this.bottomButtonBgColors,
      // this.bottomButtonBorderColors,
      required this.drawerGlobalKey,
      super.key})
      : assert(((isSupportDrag == true && onDrop != null) ||
                isSupportDrag == false) &&
            (drawerData != null || customDrawerContent != null));

  @override
  State<KqDrawer<T>> createState() => KqDrawerState<T>();
}

class KqDrawerState<T> extends State<KqDrawer<T>> {
  List<T> _drawerData = [];

  @override
  void initState() {
    super.initState();
    getDrawDataSource();
  }

  getDrawDataSource() {
    if (widget.drawerData != null) {
      var data = widget.drawerData?.call();
      if (data != null) {
        _drawerData = data;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double top = widget.top ?? KqScreenUtil().statusBarHeight + 42.r;
    return Container(
      padding: EdgeInsets.only(top: top),
      child: Drawer(
        width: widget.width ?? 300.r,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            renderTitleBar(),
            Expanded(child: renderDrawerContent()),
            renderBottomButton()
          ],
        ),
      ),
    );
  }

  Widget renderTitleBar() {
    if (widget.titleBar != null) {
      return renderTitleBar();
    } else {
      return Container(
        color: KqThemeColors.bgF4,
        height: 44.r,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: renderTitleBarContent(),
          ),
        ),
      );
    }
  }

  List<Widget> renderTitleBarContent() {
    List<Widget> children = [];
    KqInkWell ink = KqInkWell(
        onTap: () => widget.drawerPositionType ==
                DrawerPositionType.drawerPositionTypeLeft
            ? widget.drawerGlobalKey.currentState?.closeDrawer()
            : widget.drawerGlobalKey.currentState?.closeEndDrawer(),
        child: Image.asset(
          KqImages.commonIcGuanbi,
          width: 20.r,
          height: 20.r,
          fit: BoxFit.fill,
          package: KqGlobal.packageName,
        ));
    Expanded pand = Expanded(
        child: Text(
      widget.title ?? '视图筛选/排序',
      style: widget.titleStyle ??
          TextStyle(fontSize: 14.r, color: KqThemeColors.text26),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    ));

    if (widget.drawerPositionType ==
        DrawerPositionType.drawerPositionTypeLeft) {
      children.add(pand);
      if (widget.isSupportDrag != null && widget.isSupportDrag == true) {
        Expanded drop = Expanded(
            child: Text(
          KqIntl.currentResource.drag,
          textAlign: TextAlign.right,
          style: widget.titleStyle ??
              TextStyle(fontSize: 14.r, color: KqThemeColors.text59),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ));
        children.add(drop);
      }
      children.add(SizedBox(
        width: 16.r,
      ));
      children.add(ink);
    } else {
      children.add(ink);
      children.add(SizedBox(
        width: 16.r,
      ));
      children.add(pand);
      if (widget.isSupportDrag != null && widget.isSupportDrag == true) {
        Expanded drop = Expanded(
            child: Text(
          KqIntl.currentResource.drag,
          textAlign: TextAlign.right,
          style: widget.titleStyle ??
              TextStyle(fontSize: 14.r, color: KqThemeColors.text59),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ));
        children.add(drop);
      }
    }
    return children;
  }

  Widget renderDrawerContent() {
    if (widget.drawerData != null) {
      if (widget.isSupportDrag != null && widget.isSupportDrag == true) {
        return KqDragListView(
          onReorder: (int oldIndex, int newIndex) {
            T oldData = _drawerData[oldIndex];
            _drawerData.removeAt(oldIndex);
            _drawerData.insert(newIndex, oldData);
            widget.onDrop?.call(_drawerData);
            setState(() {});
          },
          children: _drawerData.map((e) => cellManage(e)).toList(),
        );
      } else {
        return ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: _drawerData.length,
          itemBuilder: (context, index) {
            return cellManage(_drawerData[index]);
          },
        );
      }
    } else {
      if (widget.customDrawerContent != null) {
        return widget.customDrawerContent!();
      } else {
        return Container();
      }
    }
  }

  Widget cellManage(T obj) {
    String? text = widget.drawItemContent?.call(obj);
    bool? isSelect = widget.drawItemSelectStatus?.call(obj);
    return KqInkWell(
        key: widget.isSupportDrag != null && widget.isSupportDrag == true
            ? Key(text ?? '')
            : null,
        onTap: () {
          widget.onTap?.call(this, obj);
          getDrawDataSource();
          setState(() {});
        },
        child: Column(
          children: [
            SizedBox(
              height: 50.r,
              child: Row(
                children: [
                  SizedBox(
                    width: 12.r,
                    height: 1,
                  ),
                  Image.asset(
                    isSelect != null && isSelect
                        ? KqImages.commonIcChoice16CSel
                        : KqImages.commonIcChoice16Nor,
                    width: 16.r,
                    height: 16.r,
                    fit: BoxFit.contain,
                    package: KqGlobal.packageName,
                  ),
                  SizedBox(
                    width: 6.r,
                    height: 1,
                  ),
                  Expanded(
                      child: Text(
                    text ?? '',
                    style:
                        TextStyle(fontSize: 14.sp, color: KqThemeColors.text59),
                  )),
                ],
              ),
            ),
            const KqDivider()
          ],
        ));
  }

  Widget renderBottomButton() {
    if (widget.customBottomWidget != null) {
      return widget.customBottomWidget?.call(this, _drawerData) ?? Container();
    }
    return Container();
  }

  /// 外部刷新
  reload() {
    getDrawDataSource();
    setState(() {});
  }
}
